from ftplib import FTP
import os

def ftp_connect(ip,port):
    timeout = 30
    ftp = FTP()
    ftp.connect(ip,port,timeout)
    ftp.login()
    return ftp

#download from ftp
def file_down(localPath,fileName):
    localPath += fileName
    localFile = open(localPath,'wb')
    ftp.retrbinary("RETR %s"%fileName,localFile.write)
    localFile.close()
    return

def read_local_file_name(path):
    files = os.listdir(path)
    retFileList = []
    #print("local files:")
    for fileName in files:
        if  fileName.find('.mkv') >= 0 :
            #print(fileName)
            retFileList.append(fileName)
    return retFileList


if __name__ == '__main__':
    ip = '192.168.1.103'
    port = 2121
    ftp = ftp_connect(ip,port)
    #pic path
    ftp.cwd('BaiduNetdisk/video/aihuijia/')
    #backup path
    localPath = 'e:/video/aihuijia/'
    backupFileList = read_local_file_name(localPath)
    print("backupFileListLen:"+str(len(backupFileList)))
    list = ftp.nlst()
    for item in list:
        if item.find('.mkv') >= 0:
            if item not in backupFileList  :
                #print(str(backupFileList.index(item)))
                print(item)
                file_down(localPath,item)
    
    print("successful!")
    ftp.quit

